/*==========================================================================

      crand.cpp  -  Copyright (C) 1993-2005 by Don Cross

      Contains random number generator for chess.

==========================================================================*/

#include <stdlib.h>
#include <time.h>
#include "chess.h"


#define MULTIPLIER      0x015a4e35L
#define INCREMENT       1

static  INT32    Seed = 1;


static INT16 _ChessRandom ()
{
    Seed = MULTIPLIER * Seed + INCREMENT;
	INT16 r = INT16(Seed >> 16) & 0x7fff;
	if (r < 0) {
		ChessFatal ("Negative value returned by _ChessRandom");
	}
    return r;
}


int ChessRandom ( int n )
{
    static int firstTime = 1;
    if ( firstTime )
    {
        firstTime = 0;
        Seed = INT32 ( time(NULL) );
    }
    
    if ( n <= 0 )
    {
        ChessFatal ( "Non-positive argument to ChessRandom()!" );
        return 0;
    }

    int r = int(_ChessRandom()) % n;
	if (r<0 || r>=n) {
		ChessFatal ("ChessRandom is broken!");
	}
	return r;
}
